<template>
  <div
    class="diy_edit forum_edits page_i_want_to_customize"
    id="i_want_to_customize_edit"
  >
    <el-form
      :model="form"
      ref="ruleFormRef"
      :rules="rules"
      label-width="auto"
      class="edit_forum_form"
      size="large"
    >
     <el-form-item label="封面图" prop="img">
        <el-upload
          class="avatar-uploader"
          drag
          accept="image/gif, image/jpeg, image/png, image/jpg"
          action=""
          :http-request="uploadimg"
          :show-file-list="false"
        >
          <img
            v-if="form.img"
            :src="$fullUrl($banseUrl, form.img)"
            class="avatar"
          />
          <el-icon v-else><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>

      <el-form-item label="分类">
        <el-select v-model="form.type" placeholder="请选择">
          <el-option
            v-for="(obj, i) in list_forum_type"
            :key="i"
            :label="obj.name"
            :value="obj.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="tag">
        <el-input v-model="form.tag" placeholder="请输入标签"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="tag">
        <el-input type="textarea" v-model="form.description" :rows="5">
        </el-input>
      </el-form-item>
      <el-form-item label="正文" prop="content">
        <form_editor
          class="editor el_form_editor_warp"
          :form="form"
          @blur_comment="blur_comment"
          @update_comment="update_comment"
          :publish_flag="false"
        />
      </el-form-item>
      <div class="footer">
        <el-button type="primary" @click="Onsubmit" size="large"
          >提交</el-button
        >
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { ref, onMounted } from "vue";
import { $post, $get } from "@/api/Api.js";
import storageHelper from "@/libs/StorageHelper";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import {
  $get_auth,
  func,
  paramsFun,
  $fullUrl,
  formatDate,
  $banseUrl,
  $check_action,
  $getUrlParams,
  filterSensitiveWords,
} from "@/utils/utils.js";
let router = useRouter();
let store = useStore();
let token = storageHelper.getToken() || null;
let UserInfo = storageHelper.getUserInfo();
// let avatar = storageHelper.getUserInfo().avatar;
// let nickname = storageHelper.getUserInfo().nickname;
let forum_id = $getUrlParams().forum_id;
let url_add = ref("/api/forum/add");
let url_set = ref("/api/forum/set");
let url_get_obj = ref("/api/forum/get_obj");
let url_upload = ref("/api/forum/upload");
let list_forum_type = ref([]);
let disabledObj = ref({
  nickname_disabled: false,
  // email_disabled:false,
  // phone_disabled:false
});
let form = ref({
  forum_id: 0,
  title: "",
  type: "",
  hits: 0,
  source: "",
  url: "",
  tag: "",
  content: "",
  img: "",
  description: "",
});

let ruleFormRef = ref(null);
let rules = ref({
  title: [
    {
      required: true,
      message: "标题不能为空",
      trigger: "blur",
    },
  ],
  nickname: [
    {
      required: true,
      message: "昵称不能为空",
      trigger: "blur",
    },
  ],
});
//获取分类
let get_forum_type = async () => {
  let json = await $get("/api/forum_type/get_list");
  if (json.result) {
    list_forum_type.value = json.result.list;
  } else if (json.error) {
    console.error(json.error);
  }
};
// 富文本编辑器更新
let update_comment = (obj) => {
  form.value.content = obj;
};
let blur_comment = (obj) => {
  form.value.content = obj;
};
// 上传封面图
let uploadimg = (param) => {
  uploadFile(param.file, "img");
};
/**
 * 上传封面图
 * @param {Object} file 文件对象
 * @param {key} 保存键名
 */
const uploadFile = (file, key = "img") => {
  var formobj = new FormData(); // FormData 对象
  formobj.append("file", file); // 文件对象
  $upload(url_upload.value, formobj, function (json) {
    if (json.result) {
      form.value[key] = json.result.url;
    } else {
      ElMessage.error("上传失败！");
    }
  });
};
/**
 * 上传文件
 * @param {String} url 请求地址
 * @param {Object} body 请求参数
 * @param {Funciton} func 回调函数，可以为空，为空则采用await返回值
 * @return {Object} 返回请求结果
 */
let $upload = async (url, body, func) => {
  url = url.replace("~/", $banseUrl);
  if (func) {
    // 如果回调函数存在, 则采用异步
    $post(url, body, {
      headers: {
        "x-auth-token": token,
        "Content-Type": "multipart/form-data",
      },
    })
      .then((res) => {
        func(res);
      })
      .catch((res) => {
        func(res);
      });
  } else {
    // 否则采用同步
    var res = await $post(url, body, {
      headers: {
        "x-auth-token": token,
        "Content-Type": "multipart/form-data",
      },
    });
    return res;
  }
};
// 点击取消
let cancel = () => {
  router.go(-1);
};
// 点击提交
let Onsubmit = async () => {
  let valid = await ruleFormRef.value.validate();
  if (valid) {
    // 提交表单
    if(forum_id){
        // 编辑
        delete form.value.update_time;
        $post(url_set.value+"?forum_id=" + forum_id, form.value).then((res) => {
            if (res.result) {
            ruleFormRef.value.resetFields();
            router.push("/home/forum/table");
            ElMessage.success("提交成功！");
            } else if (res.error) {
            ElMessage.error(res.error.message);
            }
        });
	 
    }else{
        // 新增
        $post(url_add.value, form.value).then((res) => {
            if (res.result) {
            ruleFormRef.value.resetFields();
            router.push("/home/forum/table");
            ElMessage.success("提交成功！");
            } else if (res.error) {
            ElMessage.error(res.error.message);
            }
        });

    }
  } else {
    ElMessage.error(msg);
  }
};
// 获取留言详情
let get_forum_obj = async () => {
  var list = await $get("/api/forum/get_obj?forum_id=" + forum_id);
  form.value = list.result.obj;
};
onMounted(() => {
  get_forum_type();
  if(forum_id){
	get_forum_obj();
  }
});
</script>

<style scoped lang="less">
.diy_edit {
  width: 100%;
  .edit_forum_form {
    max-width: 60%;
    margin: 90px auto;
    .fn {
      width: 100%;
    }
  }
  img {
    width: 100px;
    height: 100px;
  }
  .edit_list_forum_sell {
    width: 80%;
    margin: 90px auto;
  }
  .footer {
    text-align: center;
  }
}
</style>
